#! /usr/bin/env php
<?php
function string_hash($data) {
    $length = strlen($data);
    if (!$length) {
        return 0;
    }

    $x = floatval(ord($data[0]) << 7);
    for ($i = 0; $i < $length; $i++) {
        $x = floatval(bin2str((100003*$x))^bin2str(ord($data[$i])));
    }

    $x = floatval(bin2str($x) ^ bin2str($length));

    return $x;
}


function string_hash1($data) {
    $length = strlen($data);
    if (!$length) {
        return 0;
    }

    $x = ord($data[0]) << 7;
    for ($i = 0; $i < $length; $i++) {
        $x = (1000003 * $x) ^ ord($data[$i]);
    }

    $x ^= $length;

    return $x;
}


function string_hash2($data) {
    $length = strlen($data);
    if (!$length) {
        return 0;
    }

    $x = (float)0;
    for ($i = ($length+1)>>1, $j = 0; $i != 0; $i--, $j++) {
        $x += ($x >> 14) + (ord($data[$j]) * 0xd2d84a61);
    }

    $x += ($x >> 14) + ($length * 0xd2d84a61);

    return $x;
}


function bin2str($v) {
    $data = chr(($v & 0xFF000000) >> 24).chr(($v & 0x00FF0000) >> 16).chr(($v & 0x0000FF00) >> 8).chr($v & 0x000000FF);

    return $data;
}


function print_hash($s) {
    $x = string_hash1($s);
    for ($shift = 0; $shift < 32; $shift++) {
        printf("[%2d] => %u\n", $shift, !!((1 << $shift) & $x));
        if (!(($shift+1) % 8)) {
            printf("\n");
        }
    }
}


function get_connection() {
    $link = mysql_pconnect('127.0.0.1', 'root', '');
    @mysql_select_db('hash_conflict');

    return $link;
}


function init_table() {
    $link = get_connection();
    $step = 1024;
    $buff = array();

    $ft1 = "(%u, 0)";
    $ft2 = "processing [%d - %d] record...\n";
    $ft3 = "INSERT INTO `hash_distributed` VALUES %s";
    $ft4 = ', ';
    for ($i = 52801535, $l = pow(2, 32); $i <= $l; $i++) {
        //$buff[] = sprintf($ft1, $i);
        $buff[] = sprintf($ft1, $i);
        if (!(($i + 1) % $step)) {
            printf($ft2, $i - $step, $i);
            //$sql = sprintf($ft3, implode($ft4, $buff));
            implode($ft4, $buff);

            //mysql_unbuffered_query($sql, $link);

            unset($buff, $sql);
            gc_collect_cycles();

            $buff = array();
        }
    }
}

if ($argc < 2) {
    printf("%s: missing command\n", $argv[0]);

    exit;
}

$func = (string)$argv[1];
if (!function_exists($func)) {
    printf("function `%s' not implemented!\n", $func);

    exit;
}

$func();

